<!--  -->
<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>SKU商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert title="注意：请先选择商品分类！" type="warning" show-icon :closable="false"></el-alert>

      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col :span="8">
          <span>选择商品分类：</span>
          <!-- 商品分类的级联选择框 -->
          <el-cascader
            v-model="selectedCateKeys"
            :options="cateList"
            :props="cateProps"
             @change="handleChange"
          ></el-cascader>
        </el-col>
        <el-col :span="12">
          <div class="text item">
             <span>选择商品：</span>
            <el-select v-model="selectProid" placeholder="请选择"  @change="getProid">
              <el-option
                v-for="item in goodsList"
                :key="item.id"
                :label="item.spuName"
                :value="item.id"
               >
              </el-option>
            </el-select>
            </div
        >
        </el-col>
      </el-row>
       <el-table :data="skuGoodsList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column
          property="skuDefaultImg"
          label="图标"
          width="130">
          <template slot-scope="scope">
      　　　　<img :src="scope.row.skuDefaultImg" class="headimag"/>
      　　</template>
        </el-table-column>
        <el-table-column label="商品名称" prop="skuName"></el-table-column>
        <el-table-column label="商品价格(元)" prop="price" width="120px"></el-table-column>
        <el-table-column label="商品重量" prop="weight" width="100px"></el-table-column>
        <el-table-column label="商品库存" prop="stockCount" width="100px"></el-table-column>
        <el-table-column label="销售量" prop="saleCount" width="100px"></el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini"
            @click="showEditDialog(scope.row)">编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeById(scope.row.skuId)"
            >删除</el-button>
          </template>
        </el-table-column>
    </el-table>
    </el-card>
    <!-- 修改商品的对话框 -->
    <el-dialog
      title="修改商品信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 内容主体 -->
      <el-form
        :model="editUserForm"
        ref="editUserFormRef"
        :rules="editUserFormRules"
        label-width="120px"
      >
        <el-form-item label="商品名称">
          <el-input v-model="editUserForm.skuName" disabled></el-input>
        </el-form-item>
        <el-form-item label="商品价格(元)" prop="price">
          <el-input v-model="editUserForm.price"></el-input>
        </el-form-item>
        <el-form-item label="商品重量(kg)" prop="weight">
          <el-input v-model="editUserForm.weight"></el-input>
        </el-form-item>
        <el-form-item label="商品库存" prop="stockCount">
          <el-input v-model="editUserForm.stockCount"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类列表
      cateList: [],
      //   级联选择框的配置对象
      cateProps: {
        expandTrigger: 'hover',
        value:"catId",
        label:'catName',
        children:"children"
      },
      //   级联选择框双向绑定对象
      selectedCateKeys: [],
      selectProid:'',
      goodsList:[],
      // 所有sku商品
      skuGoodsList:[],
       // 控制商品修改对话框
      editDialogVisible: false,
      editUserFormRules:{
        stockCount: [
           { required: true, message: '库存不能为空', trigger: 'blur' },
          ],
       
        price: [
           { required: true, message: '价格不能为空', trigger: 'blur' },
          ],
        weight: [
           { required: true, message: '重量不能为空', trigger: 'blur' },
          ],
        },
      editUserForm: {},
    };
  },
   created() {
     this.getCateList()
  },
  computed:{
     // 当前选中的二级分类Id
    getCateId () {
      if (this.selectedCateKeys.length === 2) {
        return this.selectedCateKeys[1]
      }
      return null
    },
  },
  methods: {
     // 根据获取对应的商品列表
    async getGoodsList () {
      console.log("getCateId",this.getCateId)
      const {data:res} = await this.$http.get(`/xuanmall/spumessage/getAllShopByCatalogId?catalogId=${this.getCateId}&page=1&limit=300`)
      // console.log(res)
      this.goodsList =[],
       res.page.list.forEach(value =>{
         var data = {};
         data.id = value.id
         data.spuName = value.spuName
         data.images = value.images[0]
         data.price = value.price
         data.weight = value.weight
         data.stockCount = value.stockCount
         data.publishStatus = value.publishStatus
         this.goodsList.push(data)
       })
      //  console.log(this.goodsList)
    },
    //   获取所有的商品分类列表
    async getCateList () {
      const {data:res} = await this.$http.get("/xuanmall/category/list/tree")
        if(res.code === 0){
         this.cateList = this.formatData(res.data)
        }
    },
    // 格式化数据，递归将空的children置为undefined
    formatData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          data[i].children = undefined
        } else {
          this.formatData(data[i].children)
        }
      }
      return data
      },
    getProid(){
      this.getSkuList();
    },
    // 级联选择框 选中变化 触发
    async  handleChange () {
      this.getGoodsList()
    },
    // 获取该商品下的sku信息
    async  getSkuList(){
      const{data:res} = await this.$http.get(`/xuanmall/spumessage/info/${this.selectProid}`)
      // console.log("sku商品",res)
      this.skuGoodsList = []
      if(res.code !== 0)return this.$message.error("商品列表获取失败")
      res.spuSaveVo.skus.forEach(value =>{
        this.skuGoodsList.push(value)
      })
    },
     // 通过Id删除商品
    async removeById (id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该商品, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      const { data: res } = await this.$http.post('/xuanmall/skumessage/delete' ,[id])
      if (res.code !== 0) {
        return this.$message.error('删除商品失败！')
      }
      this.$message.success('删除商品成功！')
      this.getGoodsList(); 
       this.getSkuList()
    },
     // 编辑商品信息
    async showEditDialog (row) {
      this.editUserForm = row
      this.editDialogVisible = true
    },
    // 监听修改商品对话框的关闭事件
    editDialogClosed () {
      this.$refs.editUserFormRef.resetFields()
    },
    // 修改sku信息
    async  editUser () {
      console.log("修改",this.editUserForm)
      const {data:res} = await this.$http.post('/xuanmall/skumessage/update',this.editUserForm)
      // console.log("修改",res)
      if(res.code !== 0)return this.$message.error("修改失败")
      this.$message.success("修改成功")
       this.getGoodsList();
       this.getSkuList()
       this.editDialogVisible = false
    },
  }
}

</script>
<style lang='less' scoped>
.headimag{
  height: 100px;
  width: 100px;
}
</style>